package com.bcnapps.DemoGame;

import android.graphics.Canvas;
import android.util.Log;

public class GameLoopThread extends Thread {
	private GameOne viewone;
	private GameTwo viewtwo;
	private int numview;
	static final long FPS = 30;
    private boolean running = false;
   
    public GameLoopThread(GameOne view) {
          viewone = view;
          numview = 1;
    }
    
    public GameLoopThread(GameTwo view) {
    	viewtwo = view;
    	numview = 2;
    }

    public void setRunning(boolean run) {
          running = run;
    }

    @Override
	public void run() {
    	long ticksPS = 1000/FPS;
    	long sleepTime;
    	long startTime;
    	//fps checker
    	long contms=0;
    	long lasttimecheck = System.currentTimeMillis();
    	int fps=0;
    	while (running) {
			long time =  System.currentTimeMillis();
			if(contms>1000) {
				Log.v("FPS GAME",String.valueOf(fps));
				contms=time-lasttimecheck;
				fps=1;
			}
			else {
				fps++;
				contms+=time-lasttimecheck;
			}
			lasttimecheck = time;
			Canvas c = null;
			startTime =time;
			if(numview==1) {
				try {
					c = viewone.getHolder().lockCanvas();
					synchronized (viewone.getHolder()) {
						viewone.onDraw(c);
					}
				} finally {
					if (c != null) {
						viewone.getHolder().unlockCanvasAndPost(c);
					}
				}
			}
			else if(numview==2) {
				try {
					c = viewtwo.getHolder().lockCanvas();
					synchronized (viewtwo.getHolder()) {
						viewtwo.onDraw(c);
					}
				} finally {
					if (c != null) {
						viewtwo.getHolder().unlockCanvasAndPost(c);
					}
				}
			}
			sleepTime = ticksPS-(System.currentTimeMillis() - startTime);
			try {
                if (sleepTime > 10)
                       sleep(sleepTime);
                else {
                	sleep(10);
                }
			} catch (Exception e) {}
		}
	}
}
